<template>
  <base-table-layout
    title="订单发放管理"
    :total="total"
    :current-page="currentPage"
    :page-size="pageSize"
    @update:currentPage="val => currentPage = val"
    @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-input
        v-model="searchForm.keyword"
        placeholder="农户姓名/司机姓名/烤烟品种/育苗点名称"
        style="width: 300px;"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-select v-model="searchForm.status" placeholder="状态" clearable class="filter-item" style="width: 120px">
        <el-option
          v-for="dict in statusOptions"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="resetSearch"
      >重置</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="orderList"
          border
          style="width: 100%"
        >
          <el-table-column prop="orderId" label="订单ID" width="100" />
          <el-table-column prop="deptName" label="育苗点" width="200" show-overflow-tooltip />
          <el-table-column prop="driverName" label="司机" width="120" />
          <el-table-column prop="totalQuantity" label="总数量(亩)" width="120" />
          <el-table-column prop="totalPlateQuantity" label="总盘数" width="120" />
          <el-table-column prop="statusDesc" label="状态" width="120">
            <template slot-scope="scope">
              <el-tag :type="getOrderStatusType(scope.row.status)">
                {{ scope.row.statusDesc }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="showOrderDetail(scope.row)"
              >查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 分配育苗点对话框 -->
      <el-dialog
        title="分配育苗点"
        :visible.sync="nurseryDialogVisible"
        width="600px"
        append-to-body
      >
        <el-form ref="nurseryForm" :model="nurseryForm" :rules="nurseryRules" label-width="100px">
          <el-form-item label="育苗点" prop="deptId">
            <el-cascader
              v-model="nurseryForm.deptId"
              :options="nurseryOptions"
              :props="{
                checkStrictly: true,
                value: 'deptId',
                label: 'deptName',
                emitPath: false
              }"
              placeholder="请选择育苗点"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="nurseryForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="nurseryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleNurserySubmit">确定</el-button>
        </div>
      </el-dialog>

      <!-- 分配司机对话框 -->
      <el-dialog
        title="分配司机"
        :visible.sync="driverDialogVisible"
        width="900px"
        append-to-body
      >
        <div class="filter-container">
          <el-input
            v-model="driverSearchForm.driverName"
            placeholder="司机姓名"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleDriverSearch"
          />
          <el-input
            v-model="driverSearchForm.phone"
            placeholder="手机号码"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleDriverSearch"
          />
          <el-input
            v-model="driverSearchForm.licensePlate"
            placeholder="车牌号"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleDriverSearch"
          />
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleDriverSearch"
          >搜索</el-button>
          <el-button
            class="filter-item"
            type="info"
            icon="el-icon-refresh"
            @click="resetDriverSearch"
          >重置</el-button>
        </div>

        <el-table
          v-loading="driverLoading"
          :data="driverList"
          border
          style="width: 100%"
          @row-click="handleDriverSelect"
        >
          <el-table-column prop="driverId" label="司机ID" width="100" />
          <el-table-column prop="driverName" label="姓名" width="120" />
          <el-table-column prop="phone" label="手机号码" width="150" />
          <el-table-column prop="licensePlate" label="车牌号" width="120" />
          <el-table-column prop="statusDesc" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 0 ? 'success' : 'warning'">
                {{ scope.row.status === 0 ? '空闲' : '配送中' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                :disabled="scope.row.status !== 0"
                @click.stop="handleDriverSelect(scope.row)"
              >选择</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            :current-page="driverCurrentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="driverPageSize"
            :total="driverTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleDriverSizeChange"
            @current-change="handleDriverCurrentChange"
          />
        </div>
      </el-dialog>

      <!-- 部分退单对话框 -->
      <el-dialog
        title="部分退单"
        :visible.sync="partialReturnDialogVisible"
        width="600px"
        :close-on-click-modal="false"
      >
        <div class="demand-list">
          <el-table
            v-loading="demandLoading"
            :data="currentOrderDemands"
            border
            @selection-change="handleDemandSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="growerName" label="农户姓名" />
            <el-table-column prop="seedlingType" label="烟苗品种" />
            <el-table-column prop="quantity" label="数量(亩)" />
            <el-table-column prop="plateQuantity" label="票盘数" />
            <el-table-column prop="demandTime" label="需求时间" width="100" />
          </el-table>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="partialReturnDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitPartialReturn" :loading="submitLoading">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 打印对话框 -->
      <el-dialog
        title="打印预览"
        :visible.sync="printDialogVisible"
        width="800px"
        :close-on-click-modal="false"
        append-to-body
      >
        <div class="print-container">
          <print-order-template
            :order="currentPrintOrder"
            :print-user="printUser"
            :scale="printScale"
            ref="printTemplate"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="printDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="exportPDF" :loading="exportLoading">
            <i class="el-icon-download"></i> 导出PDF
          </el-button>
          <el-button type="primary" @click="confirmPrint">确认打印</el-button>
        </div>
      </el-dialog>

      <!-- 拆单对话框 -->
      <el-dialog
        title="订单拆分"
        :visible.sync="splitOrderDialogVisible"
        width="900px"
        :close-on-click-modal="false"
        append-to-body
      >
        <div class="split-order-container">
          <!-- 原订单需求列表 -->
          <div class="original-demands">
            <h3>需求列表（请选择要拆分的需求）</h3>
            <el-table
              v-loading="demandLoading"
              :data="splitOrderDemands"
              border
              @selection-change="handleSplitDemandSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="demandId" label="需求ID" width="80" />
              <el-table-column prop="growerName" label="农户姓名" width="120" />
              <el-table-column prop="seedlingType" label="烟苗品种" width="120" />
              <el-table-column prop="quantity" label="数量(亩)" width="100" />
              <el-table-column prop="plateQuantity" label="盘数" width="100" />
              <el-table-column prop="demandTime" label="需求日期" width="180" />
              <el-table-column prop="statusDesc" label="状态" width="100">
                <template slot-scope="scope">
                  <el-tag :type="getDemandStatusType(scope.row.status)">
                    {{ scope.row.statusDesc }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 备注信息 -->
          <el-form ref="splitOrderForm" :model="splitOrderForm" :rules="splitOrderRules" label-width="100px" class="split-order-form">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="splitOrderForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-form>
          
          <div class="split-notice">
            <p>请选择司机后点击确定继续</p>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="splitOrderDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSelectDriverForSplit" :loading="splitOrderLoading">选择司机</el-button>
        </div>
      </el-dialog>

      <!-- 订单详情弹窗 -->
      <seedling-order-detail
        v-model="detailDialogVisible"
        :order-id="currentOrderId"
        @assign-nursery="handleAssignNursery"
        @assign-driver="handleAssignDriver"
        @change-driver="handleChangeDriver"
        @start-delivery="handleStartDelivery"
        @partial-return="handlePartialReturn"
        @complete-order="handleComplete"
        @print-order="handlePrint"
        @split-order="handleSplitOrder"
        @refresh="fetchOrderList"
      />
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import moment from 'moment'
import 'moment/locale/zh-cn'
import BaseTableLayout from '@/components/BaseTableLayout.vue'
import PrintOrderTemplate from '@/components/PrintOrderTemplate.vue'
import SeedlingOrderDetail from '@/components/SeedlingOrderDetail.vue'
import html2pdf from 'html2pdf.js'

export default {
  name: 'SeedlingOrder',
  components: {
    BaseTableLayout,
    PrintOrderTemplate,
    SeedlingOrderDetail
  },
  data() {
    return {
      loading: false,
      searchForm: {
        keyword: '',
        status: undefined
      },
      deptOptions: [], // 部门树形数据
      statusOptions: [
        { label: '待分配', value: 0 },
        { label: '已分配育苗点', value: 1 },
        { label: '已分配司机', value: 2 },
        { label: '配送中', value: 3 },
        { label: '已完成', value: 4 },
        { label: '部分退单', value: 5 }
      ],
      orderList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 育苗点分配相关
      nurseryDialogVisible: false,
      nurseryForm: {
        orderId: null,
        deptId: null,
        remark: ''
      },
      nurseryRules: {
        deptId: [
          { required: true, message: '请选择育苗点', trigger: 'change' }
        ]
      },
      nurseryOptions: [],

      // 司机分配相关
      driverDialogVisible: false,
      driverSearchForm: {
        driverName: '',
        phone: '',
        licensePlate: ''
      },
      driverList: [],
      driverLoading: false,
      driverCurrentPage: 1,
      driverPageSize: 10,
      driverTotal: 0,
      currentOrderId: null,
      isChangeDriver: false,

      // 部分退单相关
      partialReturnDialogVisible: false,
      currentOrderDemands: [],
      selectedDemands: [],
      demandLoading: false,
      submitLoading: false,

      // 打印相关
      printDialogVisible: false,
      currentPrintOrder: null,
      printUser: '',
      printScale: 1,
      exportLoading: false,

      // 拆单相关
      splitOrderDialogVisible: false,
      splitOrderDemands: [],
      selectedSplitDemands: [],
      splitOrderForm: {
        oldOrderId: null,
        remark: ''
      },
      splitOrderRules: {
        driverId: [
          { required: true, message: '请选择司机', trigger: 'change' }
        ]
      },
      splitDriverOptions: [],
      splitDriverLoading: false,
      splitOrderLoading: false,

      // 拆单相关变量
      tempSplitData: null, // 临时存储拆单数据
      isForSplitOrder: false, // 标记当前司机选择是否用于拆单

      // 详情对话框相关
      detailDialogVisible: false,
    }
  },
  created() {
    moment.locale('zh-cn')
    this.fetchDeptTree()
    this.fetchOrderList()
    this.printUser = this.$store.state.user.name || '未知用户'
  },
  methods: {
    // 获取部门树
    async fetchDeptTree() {
      try {
        const response = await request.get('/departments/tree')
        this.deptOptions = this.filterDeptTree(response)
        this.nurseryOptions = this.filterNurseryOptions(response)
      } catch (error) {
        console.error('获取部门树失败:', error)
        this.$message.error('获取部门树失败')
      }
    },

    // 过滤部门树,只保留育苗点
    filterDeptTree(deptTree) {
      return deptTree.filter(dept => {
        if (dept.deptType === 4) { // 育苗点
          return true
        }
        if (dept.children && dept.children.length > 0) {
          dept.children = this.filterDeptTree(dept.children)
          return dept.children.length > 0
        }
        return false
      })
    },

    // 获取育苗点选项
    filterNurseryOptions(deptTree) {
      const options = []
      const traverse = (node) => {
        if (node.deptType === 4) { // 育苗点
          options.push({
            deptId: node.deptId,
            deptName: node.deptName
          })
        }
        if (node.children) {
          node.children.forEach(traverse)
        }
      }
      deptTree.forEach(traverse)
      return options
    },

    // 获取订单列表
    async fetchOrderList() {
      try {
        this.loading = true
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchForm.keyword || undefined,
          status: this.searchForm.status
        }
        const response = await request.get('/seedling/orders/page', { params })
        this.orderList = response.records
        this.total = response.total
      } catch (error) {
        console.error('获取订单列表失败:', error)
        this.$message.error('获取订单列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch: _.debounce(async function() {
      this.currentPage = 1
      await this.fetchOrderList()
    }, 300),

    resetSearch() {
      this.searchForm = {
        keyword: '',
        status: undefined
      }
      this.handleSearch()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.fetchOrderList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchOrderList()
    },

    // 分配育苗点
    handleAssignNursery(row) {
      this.nurseryForm = {
        orderId: row.orderId,
        deptId: null,
        remark: ''
      }
      this.nurseryDialogVisible = true
    },

    // 提交育苗点分配
    async handleNurserySubmit() {
      try {
        await this.$refs.nurseryForm.validate()
        await request.put(`/seedling/orders/${this.nurseryForm.orderId}/nursery/${this.nurseryForm.deptId}`)
        this.$message.success('分配育苗点成功')
        this.nurseryDialogVisible = false
        this.fetchOrderList()
      } catch (error) {
        if (error !== false) {
          console.error('分配育苗点失败:', error)
          this.$message.error('分配育苗点失败')
        }
      }
    },

    // 分配司机
    handleAssignDriver(row) {
      this.currentOrderId = row.orderId
      this.driverDialogVisible = true
      this.fetchDriverList()
    },

    // 获取司机列表
    async fetchDriverList() {
      try {
        this.driverLoading = true
        const params = {
          pageNum: this.driverCurrentPage,
          pageSize: this.driverPageSize,
          ...this.driverSearchForm
        }
        const response = await request.get('/driver/page', { params })
        this.driverList = response.records
        this.driverTotal = response.total
      } catch (error) {
        console.error('获取司机列表失败:', error)
        this.$message.error('获取司机列表失败')
      } finally {
        this.driverLoading = false
      }
    },

    handleDriverSearch: _.debounce(async function() {
      this.driverCurrentPage = 1
      await this.fetchDriverList()
    }, 300),

    resetDriverSearch() {
      this.driverSearchForm = {
        driverName: '',
        phone: '',
        licensePlate: ''
      }
      this.handleDriverSearch()
    },

    handleDriverSizeChange(val) {
      this.driverPageSize = val
      this.fetchDriverList()
    },

    handleDriverCurrentChange(val) {
      this.driverCurrentPage = val
      this.fetchDriverList()
    },

    // 选择司机
    async handleDriverSelect(row) {
      try {
        if (this.isChangeDriver) {
          // 修改司机
          await request.put(`/seedling/orders`, null, {
            params: {
              orderId: this.currentOrderId,
              driverId: row.driverId
            }
          });
          this.$message.success('修改司机成功');
        } else if (this.isForSplitOrder) {
          // 拆单选择司机
          const submitData = {
            oldOrderId: this.tempSplitData.oldOrderId,
            demandIds: this.tempSplitData.demandIds,
            driverId: row.driverId,
            remark: this.tempSplitData.remark || undefined
          }
          
          this.splitOrderLoading = true
          await request.post('/seedling/orders/split', submitData)
          this.$message.success('拆单成功')
          this.isForSplitOrder = false
          this.tempSplitData = null
        } else {
          // 分配司机
          await request.put(`/seedling/orders/${this.currentOrderId}/driver/${row.driverId}`);
          this.$message.success('分配司机成功');
        }
        this.driverDialogVisible = false;
        this.fetchOrderList();
      } catch (error) {
        console.error(this.isChangeDriver ? '修改司机失败:' : 
                     (this.isForSplitOrder ? '拆单失败:' : '分配司机失败:'), error);
        const errorMsg = error.response?.data?.msg || 
                        (this.isChangeDriver ? '修改司机失败' : 
                        (this.isForSplitOrder ? '拆单失败' : '分配司机失败'));
        this.$message.error(errorMsg);
      } finally {
        this.isChangeDriver = false;
        this.splitOrderLoading = false;
        this.isForSplitOrder = false;
      }
    },

    // 修改司机
    handleChangeDriver(row) {
      this.isChangeDriver = true;
      this.currentOrderId = row.orderId;
      this.driverDialogVisible = true;
      this.fetchDriverList();
    },

    // 打开部分退单对话框
    async handlePartialReturn(row) {
      try {
        this.demandLoading = true
        // 获取订单详情
        const response = await request.get(`/seedling/orders/${row.orderId}`)
        // 过滤出未退单的需求
        this.currentOrderDemands = response.demands.filter(demand => demand.status !== 6)
        this.currentOrder = row
        this.partialReturnDialogVisible = true
      } catch (error) {
        console.error('获取订单详情失败:', error)
        this.$message.error('获取订单详情失败')
      } finally {
        this.demandLoading = false
      }
    },

    // 处理需求选择变化
    handleDemandSelectionChange(selection) {
      this.selectedDemands = selection
    },

    // 提交部分退单
    async submitPartialReturn() {
      if (this.selectedDemands.length === 0) {
        this.$message.warning('请选择需要退单的需求')
        return
      }

      try {
        this.submitLoading = true
        const params = {
          orderId: this.currentOrder.orderId,
          returnDemandIds: this.selectedDemands.map(item => item.demandId)
        }
        await request.post('/seedling/orders/partial-return', params)
        this.$message.success('部分退单成功')
        this.partialReturnDialogVisible = false
        this.fetchOrderList()
      } catch (error) {
        if (error.response?.data?.msg) {
          this.$message.error(error.response.data.msg)
        } else {
          this.$message.error('部分退单失败')
        }
        console.error('部分退单失败:', error)
      } finally {
        this.submitLoading = false
      }
    },

    // 完成订单
    async handleComplete(row) {
      try {
        await this.$confirm('确认完成该订单吗？', '提示', {
          type: 'warning'
        })
        await request.put(`/seedling/orders/${row.orderId}/status/4`)
        this.$message.success('订单已完成')
        this.fetchOrderList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('完成订单失败:', error)
          this.$message.error('完成订单失败')
        }
      }
    },

    // 开始配送
    async handleStartDelivery(row) {
      try {
        await this.$confirm('确认开始配送该订单吗?', '提示', {
          type: 'warning'
        })
        await request.put(`/seedling/orders/${row.orderId}/status/3`)
        this.$message.success('订单已开始配送')
        this.fetchOrderList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('开始配送失败:', error)
          this.$message.error('开始配送失败')
        }
      }
    },

    // 获取订单状态类型
    getOrderStatusType(status) {
      const statusMap = {
        0: 'warning',   // 待分配
        1: 'primary',   // 已分配育苗点
        2: 'success',   // 已分配司机
        3: 'warning',   // 配送中
        4: 'success',   // 已完成
        5: 'danger'     // 部分退单
      }
      return statusMap[status] || 'info'
    },

    // 获取需求状态类型
    getDemandStatusType(status) {
      const statusMap = {
        0: 'warning',   // 待分配
        1: 'primary',   // 已生成订单
        2: 'success',   // 已分配育苗点
        3: 'info',      // 已分配司机
        4: 'warning',   // 配送中
        5: 'success',   // 已完成
        6: 'danger',    // 已退单
        7: 'info'       // 已取消
      }
      return statusMap[status] || 'info'
    },

    // 处理打印
    async handlePrint(row) {
      try {
        // 获取订单详情
        const response = await request.get(`/seedling/orders/${row.orderId}`)
        
        // 获取司机详细信息
        if (response.driverId) {
          const driverInfo = await request.get(`/driver/${response.driverId}`)
          response.driverPhone = driverInfo.phone
          response.licensePlate = driverInfo.licensePlate
        }
        
        this.currentPrintOrder = {
          ...response,
          deliveryDate: response.updateTime
        }
        
        // 从store中获取打印人信息
        const userInfo = this.$store.state.userInfo
        this.printUser = userInfo ? userInfo.realName : '未知用户'
        this.printDialogVisible = true
      } catch (error) {
        console.error('获取订单详情失败:', error)
        this.$message.error('获取订单详情失败')
      }
    },

    // 确认打印
    async confirmPrint() {
      try {
        // 设置缩放为0.8
        this.printScale = 0.8
        await this.$nextTick()

        // 创建打印样式
        const printStyle = document.createElement('style')
        printStyle.innerHTML = `
          @media print {
            body * {
              visibility: hidden;
            }
            .print-template, .print-template * {
              visibility: visible;
              -webkit-print-color-adjust: exact;
              print-color-adjust: exact;
            }
            .print-template {
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              padding: 20px;
              box-sizing: border-box;
            }
            @page {
              size: A4;
              margin: 10mm;
            }
          }
        `
        document.head.appendChild(printStyle)
        
        // 执行打印
        window.print()
        
        // 移除打印样式
        document.head.removeChild(printStyle)
        
        // 恢复缩放并关闭打印对话框
        this.printDialogVisible = false
      } catch (error) {
        console.error('打印失败:', error)
        this.$message.error('打印失败')
        this.printScale = 1
      }
    },

    async exportPDF() {
      try {
        // 设置缩放为0.8
        this.printScale = 0.8
        await this.$nextTick()
        
        const element = this.$refs.printTemplate.$refs.printTemplate
        const opt = {
          margin: [5, 5],
          filename: `配送单_${this.currentPrintOrder.orderId}.pdf`,
          image: { type: 'png', quality: 1 },
          html2canvas: { 
            scale: 3,
            letterRendering: true,
            useCORS: true,
            logging: false
          },
          jsPDF: { 
            unit: 'mm', 
            format: 'a4', 
            orientation: 'portrait'
          }
        }
        
        await html2pdf().set(opt).from(element).save()
        this.$message.success('PDF导出成功')
        
        // 导出完成后恢复缩放
        this.printScale = 1
      } catch (error) {
        console.error('PDF导出失败:', error)
        this.$message.error('PDF导出失败')
        this.printScale = 1
      }
    },

    // 处理拆单
    async handleSplitOrder(row) {
      try {
        this.demandLoading = true
        
        // 获取订单详情
        const response = await request.get(`/seedling/orders/${row.orderId}`)
        if (!response.demands || response.demands.length <= 1) {
          this.$message.warning('该订单需求数量不足，无法拆分')
          return
        }
        
        // 初始化拆单数据
        this.splitOrderDemands = response.demands.filter(d => d.status !== 6 && d.status !== 7) // 过滤掉已退单和已取消的需求
        this.splitOrderForm = {
          oldOrderId: row.orderId,
          remark: ''
        }
        
        // 显示拆单对话框
        this.splitOrderDialogVisible = true
      } catch (error) {
        console.error('获取订单详情失败:', error)
        this.$message.error('获取订单详情失败')
      } finally {
        this.demandLoading = false
      }
    },
    
    // 拆单需求选择变化
    handleSplitDemandSelectionChange(selection) {
      this.selectedSplitDemands = selection
    },
    
    // 为拆单选择司机
    handleSelectDriverForSplit() {
      // 检查是否选择了需求
      if (!this.selectedSplitDemands.length) {
        this.$message.warning('请选择要拆分的需求')
        return
      }
      
      // 保存当前选择的需求和备注信息
      this.tempSplitData = {
        oldOrderId: this.splitOrderForm.oldOrderId,
        demandIds: this.selectedSplitDemands.map(item => item.demandId),
        remark: this.splitOrderForm.remark
      }
      
      // 设置标志以区分普通司机选择和拆单司机选择
      this.isForSplitOrder = true
      
      // 关闭拆单对话框，打开司机选择对话框
      this.splitOrderDialogVisible = false
      this.currentOrderId = this.splitOrderForm.oldOrderId
      this.driverDialogVisible = true
      this.fetchDriverList()
    },

    // 显示订单详情
    showOrderDetail(row) {
      this.currentOrderId = row.orderId
      this.detailDialogVisible = true
    },

    // 快速命令处理
    handleQuickCommand(command, row) {
      switch (command) {
        case 'assignNursery':
          this.handleAssignNursery(row)
          break
        case 'assignDriver':
          this.handleAssignDriver(row)
          break
        case 'startDelivery':
          this.handleStartDelivery(row)
          break
        case 'partialReturn':
          this.handlePartialReturn(row)
          break
        case 'complete':
          this.handleComplete(row)
          break
        case 'changeDriver':
          this.handleChangeDriver(row)
          break
        case 'print':
          this.handlePrint(row)
          break
        case 'splitOrder':
          this.handleSplitOrder(row)
          break
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.button-group {
  .button-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 5px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .el-button {
      width: 85px;
      padding: 5px 4px;
      margin: 0 2px;
      
      &:first-child {
        margin-left: 0;
      }
      
      &:last-child {
        margin-right: 0;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}

.filter-item {
  margin-left: 10px;
}

.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  padding: 10px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
}

.table-container {
  position: relative;
}

.demand-list {
  margin-bottom: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.print-container {
  position: relative;
  padding: 20px;
  
  .print-actions {
    position: absolute;
    top: 20px;
    right: 20px;
    z-index: 1;
    
    @media print {
      display: none;
    }
  }
}

.split-order-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  
  .original-demands {
    h3 {
      margin-top: 0;
      margin-bottom: 10px;
      font-size: 16px;
      color: #606266;
    }
  }
  
  .split-order-form {
    width: 100%;
  }
  
  .split-notice {
    color: #909399;
    text-align: center;
    font-size: 14px;
    margin-top: 10px;
  }
}
</style> 